package com.example.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Random;

@Aspect
@Component
public class OrderAspect {

 
    @Pointcut("execution(* com.example.service.OrderService.*(..))")
    public void orderServiceMethods() {}

   
    @Pointcut("execution(* com.example.service.OrderService.add(..)) || " +
            "execution(* com.example.service.OrderService.delete(..))")
    public void addAndDeleteMethods() {}

  
    @Before("orderServiceMethods()")
    public void beforeAdvice() {
        System.out.println("hello, 我是一个前置增强");
    }

  
    @After("addAndDeleteMethods()")
    public void afterAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

   
    @AfterReturning(pointcut = "orderServiceMethods()", returning = "result")
    public void afterReturningAdvice(Object result) {
        System.out.println("方法的返回值为: " + result);
    }

  
    @Around("orderServiceMethods()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        System.out.println("方法执行时间: " + (end - start) + "ms");
        return result;
    }

   
    @Around("addAndDeleteMethods()")
    public Object permissionCheck(ProceedingJoinPoint joinPoint) throws Throwable {
       
        Random random = new Random();
        int permission = random.nextInt(2); 

        if (permission == 0) {
            System.out.println("权限检查通过，有权限执行操作");
            return joinPoint.proceed();
        } else {
            System.out.println("权限检查未通过，无权限执行操作");
            return null;
        }
    }
}
